﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;

using Truextend.Training.Presenter.ViewInterfaces;
using Truextend.Training.Model.Entities;
using Truextend.Training.Presenter;
using Microsoft.SharePoint;
using System.Collections;
using System.Collections.Generic;

namespace Truextend.Training.CourseForm
{
    public partial class CourseFormUserControl : UserControl, ICourseInstanceDetailView
    {
        string TITLE = "Detail Instance for Course \"{0}\" ({1})";

        PageMode pageMode;
        CourseInstanceDetailPresenter pagePresenter;
        Course course = null;

        protected void Page_Init(object sender, EventArgs e)
        {
            HideMessageErrors();
            dtcStartDate.SelectedDate = DateTime.Today;
            dtcEndDate.SelectedDate = DateTime.Today;
            //pagePresenter = new CourseInstanceDetailPresenter(Request.QueryString[AsCodeNames.PublicAlertId], this);
            pagePresenter = new CourseInstanceDetailPresenter(Request.QueryString["courseid"], Request.QueryString["instanceid"], this);
            pageMode = pagePresenter.PageMode;
            pagePresenter.InitControls();

            if (!IsPostBack && pageMode == PageMode.Edition)
            {
                pagePresenter.LoadCourseInstanceDataInView();
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            HideMessageErrors();
            dtcStartDate.SelectedDate = DateTime.Today;
            dtcEndDate.SelectedDate = DateTime.Today;
        }

        #region ICourseInstanceDetailView Members

        /// <summary>
        /// Properties to put and get data to/from the view
        /// </summary>
        
        public Course Course
        {
            set 
            {
                if (pageMode == PageMode.New)
                {
                    lbMsgPageMode.Text = TITLE.Replace("{0}", value.Name).Replace("{1}", "New");
                }
                
                if (pageMode == PageMode.Edition)
                {
                    lbMsgPageMode.Text = TITLE.Replace("{0}", value.Name).Replace("{1}", "Edit");
                }

                course = value;
                //Session["course"] = value;
            }
            get {
                string id = Request.QueryString["courseid"];
                
                return CourseInstanceDetailPresenter.GetCourse(id); 
            }
        }

        public string CourseName
        {
            get
            {
                throw new NotImplementedException();
            }
            set
            {
                if (pageMode == PageMode.Edition)
                {
                    //txCourseName.Text = "edit";
                }
            }
        }

        public string CourseCategory
        {
            get
            {
                throw new NotImplementedException();
            }
            set
            {
                throw new NotImplementedException();
            }
        }

        public string Location
        {
            get
            {
                return txLocation.Text;
            }
            set
            {
                txLocation.Text = value;
            }
        }

        public DateTime StartDate
        {
            get
            {
                try
                {
                    return dtcStartDate.SelectedDate;
                }
                catch (Exception e)
                {
                    return new DateTime(1, 1, 1);
                }
            }
            set
            {
                dtcStartDate.SelectedDate = value;
            }
        }

        public DateTime EndDate
        {
            get
            {
                try
                {
                    return dtcEndDate.SelectedDate;
                }
                catch(Exception e)
                {
                    return new DateTime(1, 1, 1);
                }
            }
            set
            {
                dtcEndDate.SelectedDate = value;
            }
        }

        public int InstructorId
        {
            set 
            {
                //peInstructor.SelectionSet = value.ToString();
                SPSite site = SPContext.Current.Site;
                SPWeb web = site.OpenWeb();
                SPUser instructor = web.AllUsers.GetByID(value);
                peInstructor.CommaSeparatedAccounts = instructor.Name;
            }
            get
            {
                try
                {
                    SPUser lUser = SPContext.Current.Web.AllUsers[peInstructor.Accounts[0].ToString()];
                    return lUser.ID;
                }
                catch (Exception e)
                {
                    return 0;
                }
            }
        }

        public PageMode PageModeInTitle
        {
            set 
            {
                //lbMsgPageMode.Text = "Course Version Detail ("+pageMode.ToString()+")";
            }
        }
        
        public List<string> DaysWeek 
        {
            get
            {
                List<string> days = new List<string>();
                foreach(ListItem item in clRecurrence.Items )
                {
                    if (item.Selected)
                    {
                        days.Add(item.Text);
                    }
                }
                return days;
            }
            set
            {
                foreach (string day in value)
                {
                    foreach (ListItem item in clRecurrence.Items)
                    {
                        if (item.Text.Equals(day))
                        {
                            item.Selected = true;
                        }
                    }
                }
            }
        }

        #endregion

        protected void btSave_Click(object sender, EventArgs e)
        {
        
            if(pagePresenter.InformationIsValid())
            {
                if (pageMode == PageMode.New)
                {
                    string id = Request.QueryString["courseid"];
                    this.Course = CourseInstanceDetailPresenter.GetCourse(id);
                    pagePresenter.OnSave(this.Course);
                }
                else if (pageMode == PageMode.Edition)
                {
                    string id = Request.QueryString["instanceid"];
                    //CourseInstance instance = CourseInstanceDetailPresenter.GetCourseInstance(id);
                    pagePresenter.OnUpdate(id);
                }
            }
        }

        protected void btCancel_Click(object sender, EventArgs e)
        {
            RedirectToCourseInstanceManageList();
        }

        public void RedirectToCourseInstanceManageList()
        {
            string url = SPContext.Current.Web.Url + "/_layouts/Truextend.Training/Pages/CourseManageListPage.aspx";
            Response.Redirect(url);
        }

        public void LoadDaysWeek()
        {
            List<string> daysList = new List<string>();

            daysList.Add("Monday");
            daysList.Add("Tuesday");
            daysList.Add("Wednesday");
            daysList.Add("Thursday");
            daysList.Add("Friday");

            clRecurrence.DataSource = daysList;
            clRecurrence.DataBind();
        }

        public string Message
        {
            get
            {
                throw new NotImplementedException();
            }
            set
            {
                throw new NotImplementedException();
            }
        }

        public void SetError(string messageError, ViewPanelError viewPanelError)
        {
            switch (viewPanelError)
            {
                case ViewPanelError.Location:
                    plLocatioError.Visible = true;
                    lbLocationError.Text = messageError;
                    break;
                case ViewPanelError.Dates:
                    plDatesError.Visible = true;
                    lbDatesError.Text = messageError;
                    break;
                case ViewPanelError.Recurrence:
                    plRecurrenceError.Visible = true;
                    lbRecurrenceError.Text = messageError;
                    break;
                case ViewPanelError.Instructor:
                    plInstructorError.Visible = true;
                    lbInstructorError.Text = messageError;
                    break;
                default:
                    break;
            }
        }

        private void HideMessageErrors()
        {
            plLocatioError.Visible = false;
            plDatesError.Visible = false;
            plRecurrenceError.Visible = false;
            plInstructorError.Visible = false;
        }
    }
}
